﻿extern alias GlobalCamera;

using HalconDotNet;
using Station.Common.Rejudgment;
using Station.Inspect;
using Station.Inspect.Rejudgment;
using System;
using System.Collections.Generic;
using System.Data;
using System.Drawing;
using System.IO;
using System.Net;
using System.Threading;
using System.Windows.Forms;
using thinger.VisionModels;
using thinger.VisitionDAL;

namespace thinger.VisionDemo
{
	public class Mainpro
	{
		public Mainpro()
		{
			TcpRecive.Read.OnTCPClientRecive += OnTCPReadRecive;
			TcpRecive.Print.OnTCPClientRecive += OnTCPPrintRecive;
			//TcpServer.Instance.OnTCPSeverRecive += OnRobotRecive;
		}

		public void Bang(H5U h5u, SysConfig sysConfig)
		{
			this.h5u = h5u;
			//this.ThreadControl = ThreadControl;
			this.sysConfig = sysConfig;
		}

		private H5U h5u = new H5U();
		private SysConfig sysConfig = new SysConfig();

		//public bool ThreadControl;
		public event EventHandler<string> OnAddLogRecive;

		public event EventHandler<string> OnOneAddLogRecive;

		public event EventHandler OnOneRunRecive;

		public event EventHandler<int> OnChangeRowRecive;

		public event EventHandler<ImgMsg> OnGetRowRecive;

		//
		public event EventHandler OnMapChangeRecive;

		public event EventHandler<string> OnOneWarnRecive;

		private Position getPosition = new Position();
		private string SaveBasePath = Application.StartupPath + "\\SaveImage";
		private HObject hImage = new HObject();

		private static Mainpro instance;
		private static object instanceLock = new object();

		public static Mainpro Instance
		{
			get
			{
				if (instance == null)
				{
					lock (instanceLock)
					{
						if (instance == null)
						{
							instance = new Mainpro();
						}
					}
				}
				return instance;
			}
		}

		public bool IsAutoRun;

		public void AddLog(int n, string str)
		{
			OnAddLogRecive?.Invoke(this, $"{n},{str}");
		}

		//--- mapping设置消息处理
		public void DoMapChangeMsg()
		{
			OnMapChangeRecive?.Invoke(this, EventArgs.Empty);
		}

		//--- 报警信息处理
		public void DoWarnMsg(string msg)
		{
			OnOneWarnRecive?.Invoke(this, msg);
		}

		//--- 半自动运行
		public void DoAutoRun()
		{
			OnOneRunRecive?.Invoke(this, EventArgs.Empty);
		}

		//--- 手动界面消息
		public void DoOneMsg(string str)
		{
			OnOneAddLogRecive?.Invoke(this, str);
		}

		//---- 报警界面

		#region 数据表格+cell窗口

		public void ChangeRow(int n)
		{
			OnChangeRowRecive?.Invoke(this, n);
		}

		public void GetRow(ImgMsg row)
		{
			OnGetRowRecive?.Invoke(this, row);
		}

		#endregion 数据表格+cell窗口

		#region 功能封装

		public void Check_Run_A(int n)
		{
			selectedModeChanged();//检测模式
			while (GlobalVar.Instance.ThreadControl)//等待数据
			{
				if (GlobalVar.Instance.getFinished)
				{
					break;
				}
				if (n == 1)
				{
					AddLog(0, $"搬运{n}-等待搬运2-数据保存完成");
				}
				else
				{
					AddLog(0, $"搬运{n}-等待搬运1-数据保存完成");
				}
				Thread.Sleep(1500);
			}
			AddLog(0, $"搬运{n}-开始检测");
			GlobalVar.Instance.getFinished = false;
			while (GlobalVar.Instance.ThreadControl)
			{
				if (!StaInspect.Instance.IsBusy())
					break;
				Thread.Sleep(1500);
			}
			GlobalVar.Instance.linenumCH = n;
			if (n == 1)
			{
				StaInspect.Instance.initSwitch(0);//设置检测模式
												  //StaInspect.Instance.SwitchPrj(0);//设置检测模式
			}
			else
			{
				StaInspect.Instance.initSwitch(0, 3);//设置检测模式
													 //StaInspect.Instance.SwitchPrj(0, 3);//设置检测模式
			}

			StaInspect.Instance.apasscount = 0;
			StaInspect.Instance.agoodcount = 0;
			StaInspect.Instance.acheckcount = 0;
			StaInspect.Instance.adefectcount = 0;

			StaInspect.Instance.pici = sysConfig.dama_pici;
			StaInspect.Instance.CellNGCount = sysConfig.ngCount;
			StaInspect.Instance.IsCellNGMax = sysConfig.chc_ng;
			//StaInspect.Instance.RecheckClose = false;
			StaInspect.Instance.Prj.g_dMaxVel = 1000;
			StaInspect.Instance.RejudgEnable = sysConfig.ReCheck;
			StaInspect.Instance.isMakeBigImg = sysConfig.isMakeBigImg;
			Thread.Sleep(10);
			AddLog(0, $"搬运{n}-A面Z轴高度：" + StaInspect.Instance.Rbt.GetCurPos().z.ToString());
			if (StaInspect.Instance.RejudgEnable)
			{
				StaInspect.Instance.RecheckClose = false;
				StaInspect.Instance.IsCheckOpen = false;
			}
			else
			{
				StaInspect.Instance.IsCheckOpen = true;
				StaInspect.Instance.RecheckClose = true;
			}
			StaInspect.Instance.StartInspect();
			while (GlobalVar.Instance.ThreadControl)
			{
				if (!StaInspect.Instance.IsBusy())
					break;
				Thread.Sleep(100);
			}
			Thread.Sleep(11);
			AddLog(0, $"搬运{n}-A面检测采集图完成");
			////复判窗口关闭
			while (GlobalVar.Instance.ThreadControl)
			{
				if (StaInspect.Instance.IsMarkBaofei)
				{
					AddLog(0, $"搬运{n}-纠偏失败");
					break;
				}

				if (StaInspect.Instance.IsBaofei)
				{
					AddLog(0, $"搬运{n}-物料报废");
					break;
				}
				if (StaInspect.Instance.RecheckClose)
				{
					AddLog(0, $"搬运{n}-复判窗口关闭");
					break;
				}
				Thread.Sleep(100);
			}

			if (StaInspect.Instance.Mode != WorkMode.OA)
			{
				if (DoIsBaofeiA(n))
				{
					GlobalVar.Instance.getFinished = true;
					return;
				}
				if (n == 1)
				{
					//检测A面完成给信号
					var result = h5u.WriteH5U(4024, "11");//检测A面完成给信号
					if (result.IsSuccess)
					{
						//GlobalVar.Instance.getFinished = true;
						GlobalVar.Instance.currplc_step1++;
						AddLog(0, $"搬运{n}-A面检测完成");
					}
				}
				else
				{
					var result = h5u.WriteH5U(4064, "11");//检测A面完成给信号
					if (result.IsSuccess)
					{
						//GlobalVar.Instance.getFinished = true;
						GlobalVar.Instance.currplc_step2++;
						AddLog(0, $"搬运{n}-A面检测完成");
					}
				}
				return;
			}

			while (GlobalVar.Instance.ThreadControl)
			{
				if (StaInspect.Instance.canvasB == null || StaInspect.Instance.canvasA == null)
				{
					AddLog(1, $"搬运{n}-大图保存失败");
					break;
				}

				if (GlobalVar.Instance.getFinished)
				{
					AddLog(0, $"搬运{n}-检测A数据处理完成");
					break;
				}
				Thread.Sleep(100);
			}
			if (DoIsBaofeiA(n))
			{
				GlobalVar.Instance.getFinished = true;
				return;
			}
			if (n == 1)
			{
				//检测A面完成给信号
				var result = h5u.WriteH5U(4024, "11");//检测A面完成给信号
				if (result.IsSuccess)
				{
					AddLog(0, $"搬运{n}-A面检测完成,开始B面");
					//while (GlobalVar.Instance.ThreadControl)
					//{
					//    if (GlobalVar.Instance.getFinished)
					//    {
					//        AddLog(0, $"搬运{n}-数据接收完毕");
					//        break;
					//    }
					//    Thread.Sleep(100);
					//}
					//currplc_step1++;
				}
			}
			else
			{
				var result = h5u.WriteH5U(4064, "11");//检测A面完成给信号
				if (result.IsSuccess)
				{
					AddLog(0, $"搬运{n}-A面检测完成,开始B面");
					//while (GlobalVar.Instance.ThreadControl)
					//{
					//    if (GlobalVar.Instance.getFinished && getDoDaMa)
					//    {
					//        AddLog(0, $"搬运{n}-数据接收完毕");
					//        break;
					//    }
					//    Thread.Sleep(100);
					//}
					//currplc_step2++;
				}
			}
		}

		public void Check_Run_B(int n)
		{
			selectedModeChanged();//检测模式
								  //while (GlobalVar.Instance.ThreadControl)
								  //{
								  //    if (!StaInspect.Instance.IsBusy())
								  //        break;
								  //    Thread.Sleep(100);

			//}
			if (n == 1)
			{
				StaInspect.Instance.initSwitch(1);//设置检测模式
			}
			else
			{
				StaInspect.Instance.initSwitch(1, 4);//设置检测模式
			}
			StaInspect.Instance.bpasscount = 0;
			StaInspect.Instance.bgoodcount = 0;
			StaInspect.Instance.bcheckcount = 0;
			StaInspect.Instance.bdefectcount = 0;

			StaInspect.Instance.pici = sysConfig.dama_pici;
			StaInspect.Instance.CellNGCount = sysConfig.ngCount;
			StaInspect.Instance.IsCellNGMax = sysConfig.chc_ng;
			StaInspect.Instance.Prj.g_dMaxVel = 1000;
			StaInspect.Instance.RejudgEnable = sysConfig.ReCheck;
			StaInspect.Instance.isMakeBigImg = sysConfig.isMakeBigImg;
			AddLog(0, $"搬运{n}-B面Z轴高度：" + StaInspect.Instance.Rbt.GetCurPos().z.ToString());

			if (StaInspect.Instance.RejudgEnable)
			{
				StaInspect.Instance.RecheckClose = false;
				StaInspect.Instance.IsCheckOpen = false;
			}
			else
			{
				StaInspect.Instance.IsCheckOpen = true;
				StaInspect.Instance.RecheckClose = true;
			}

			StaInspect.Instance.StartInspect();
			Thread.Sleep(1500);
			AddLog(0, $"搬运{n}-B面检测采集图等待中");
			while (GlobalVar.Instance.ThreadControl)
			{
				if (!StaInspect.Instance.IsBusy())
					break;
				Thread.Sleep(1500);
			}
			AddLog(0, $"搬运{n}-B面检测采集图完成");
			////复判窗口关闭
			while (GlobalVar.Instance.ThreadControl)
			{
				if (StaInspect.Instance.IsMarkBaofei)
				{
					AddLog(0, $"搬运{n}-纠偏失败");
					break;
				}

				if (StaInspect.Instance.IsBaofei)
				{
					AddLog(0, $"搬运{n}-物料报废");
					break;
				}
				if (StaInspect.Instance.RecheckClose)
				{
					AddLog(0, $"搬运{n}-复判窗口关闭");
					break;
				}
				Thread.Sleep(100);
			}

			while (GlobalVar.Instance.ThreadControl)
			{
				if (GlobalVar.Instance.getFinished)
				{
					AddLog(0, $"搬运{n}-检测B数据完成");
					break;
				}
				Thread.Sleep(100);
			}

			if (DoIsBaofeiB(n))
			{
				GlobalVar.Instance.getFinished = true;
				return;
			}

			if (n == 1)
			{
				//扫码B面完成给信号
				var result = h5u.WriteH5U(4026, "11");//扫码B面完成给信号
				if (result.IsSuccess)
				{
					AddLog(0, $"搬运{n}-检测完成");
					//while (GlobalVar.Instance.ThreadControl)
					//{
					//    if (GlobalVar.Instance.getFinished)
					//    {
					//        AddLog(0, $"搬运{n}-数据接收完毕");
					//        break;
					//    }
					//    Thread.Sleep(100);
					//}
					//currplc_step1++;
				}
			}
			else
			{
				//检测B面完成给信号
				var result = h5u.WriteH5U(4066, "11");//检测B面完成给信号
				if (result.IsSuccess)
				{
					AddLog(0, $"搬运{n}-检测完成");
					//while (GlobalVar.Instance.ThreadControl)
					//{
					//    if (GlobalVar.Instance.getFinished)
					//    {
					//        AddLog(0, $"搬运{n}-数据接收完毕");
					//        break;
					//    }
					//    Thread.Sleep(100);
					//}
					// currplc_step2++;
				}
			}
		}

		public bool DoIsBaofeiA(int n)
		{
			if (StaInspect.Instance.IsBaofei || StaInspect.Instance.IsMarkBaofei)
			{
				string po_pathh = "报废时间" + DateTime.Now.ToString("yyyy-MM-dd HH：mm：ss");
				if (StaInspect.Instance.IsMarkBaofei)
				{
					po_pathh = "匹配失败时间" + DateTime.Now.ToString("yyyy-MM-dd HH：mm：ss");
					LogRecord.WriteMarkLog(StaInspect.Instance.loadPath + "\\Record", DateTime.Now.ToString("yyyy-MM-dd") + "纠偏失败.txt", po_pathh + "  位置:" + (GlobalVar.Instance.CurrNumNG + 1));
				}
				if (n == 1)
				{
					string po_path = StaInspect.Instance.loadPath + "\\Savemap\\" + po_pathh;
					try
					{
						// 确保code文件夹存在
						if (Directory.Exists(GlobalVar.Instance.OrderData1.path))
						{
							// 确保新的文件夹名不存在
							if (!Directory.Exists(po_path))
							{
								Microsoft.VisualBasic.FileIO.FileSystem.RenameDirectory(GlobalVar.Instance.OrderData1.path, po_pathh);
							}
						}
					}
					catch (Exception ex)
					{
						Console.WriteLine("发生错误：" + ex.Message);
					}

					GlobalVar.Instance.OrderData1.IsBaoFei = true;
					//检测A面完成给信号
					var result = h5u.WriteH5U(4350, "11");//搬运1检测产品报废信号
					if (result.IsSuccess)
					{
						AddLog(0, $"搬运{n}-检测产品报废信号");
					}
					result = h5u.WriteH5U(4024, "11");//检测A面完成给信号
					if (result.IsSuccess)
					{
						GlobalVar.Instance.currplc_step1++;
						AddLog(0, $"搬运{n}-A面检测完成,此物料报废");
					}
				}
				else
				{
					string po_path = StaInspect.Instance.loadPath + "\\Savemap\\" + po_pathh;

					try
					{
						// 确保code文件夹存在
						if (Directory.Exists(GlobalVar.Instance.OrderData2.path))
						{
							// 确保新的文件夹名不存在
							if (!Directory.Exists(po_path))
							{
								Microsoft.VisualBasic.FileIO.FileSystem.RenameDirectory(GlobalVar.Instance.OrderData2.path, po_pathh);
							}
						}
					}
					catch (Exception ex)
					{
						Console.WriteLine("发生错误：" + ex.Message);
					}
					GlobalVar.Instance.OrderData2.IsBaoFei = true;

					var result = h5u.WriteH5U(4352, "11");//搬运2检测产品报废信号
					if (result.IsSuccess)
					{
						AddLog(0, $"搬运{n}-检测产品报废信号");
					}
					result = h5u.WriteH5U(4064, "11");//检测A面完成给信号
					if (result.IsSuccess)
					{
						GlobalVar.Instance.currplc_step2++;
						AddLog(0, $"搬运{n}-A面检测完成,此物料报废");
					}
				}
				return true;
			}
			else
			{
				return false;
			}
		}

		public bool DoIsBaofeiB(int n)
		{
			if (StaInspect.Instance.IsBaofei || StaInspect.Instance.IsMarkBaofei)
			{
				string po_pathh = "报废时间" + DateTime.Now.ToString("yyyy-MM-dd HH：mm：ss");
				if (StaInspect.Instance.IsMarkBaofei)
				{
					po_pathh = "匹配失败时间" + DateTime.Now.ToString("yyyy-MM-dd HH：mm：ss");
					LogRecord.WriteMarkLog(StaInspect.Instance.loadPath + "\\Record", DateTime.Now.ToString("yyyy-MM-dd") + "纠偏失败.txt", po_pathh + "  位置:" + (GlobalVar.Instance.CurrNumNG + 1));
				}
				if (n == 1)
				{
					string po_path = StaInspect.Instance.loadPath + "\\Savemap\\" + po_pathh;

					try
					{
						// 确保code文件夹存在
						if (Directory.Exists(GlobalVar.Instance.OrderData1.path))
						{
							// 确保新的文件夹名不存在
							if (!Directory.Exists(po_path))
							{
								Microsoft.VisualBasic.FileIO.FileSystem.RenameDirectory(GlobalVar.Instance.OrderData1.path, po_pathh);
							}
						}
					}
					catch (Exception ex)
					{
						Console.WriteLine("发生错误：" + ex.Message);
					}

					GlobalVar.Instance.OrderData1.IsBaoFei = true;
					//检测A面完成给信号
					var result = h5u.WriteH5U(4350, "11");//搬运1检测产品报废信号
					if (result.IsSuccess)
					{
						AddLog(0, $"搬运{n}-检测产品报废信号");
					}
					result = h5u.WriteH5U(4026, "11");//检测A面完成给信号
					if (result.IsSuccess)
					{
						GlobalVar.Instance.currplc_step1++;
						AddLog(0, $"搬运{n}-B面检测完成,此物料报废");
					}
				}
				else
				{
					string po_path = StaInspect.Instance.loadPath + "\\Savemap\\" + po_pathh;

					try
					{
						// 确保code文件夹存在
						if (Directory.Exists(GlobalVar.Instance.OrderData2.path))
						{
							// 确保新的文件夹名不存在
							if (!Directory.Exists(po_path))
							{
								Microsoft.VisualBasic.FileIO.FileSystem.RenameDirectory(GlobalVar.Instance.OrderData2.path, po_pathh);
							}
						}
					}
					catch (Exception ex)
					{
						Console.WriteLine("发生错误：" + ex.Message);
					}
					GlobalVar.Instance.OrderData2.IsBaoFei = true;
					var result = h5u.WriteH5U(4352, "11");//搬运2检测产品报废信号
					if (result.IsSuccess)
					{
						AddLog(0, $"搬运{n}-检测产品报废信号");
					}
					result = h5u.WriteH5U(4066, "11");//检测A面完成给信号
					if (result.IsSuccess)
					{
						GlobalVar.Instance.currplc_step2++;
						AddLog(0, $"搬运{n}-A面检测完成,此物料报废");
					}
				}
				return true;
			}
			else
			{
				return false;
			}
		}

		#endregion 功能封装

		#region ftp

		//上传文件
		public bool FtpUpload(string localFile, string ftpServer, string username, string password, string ftpPath)
		{
			//检查目录是否存在，不存在创建
			FtpCheckDirectoryExist(ftpPath, ftpServer, username, password);
			FileInfo fi = new FileInfo(localFile);
			FileStream fs = fi.OpenRead();
			long length = fs.Length;
			FtpWebRequest req = (FtpWebRequest)WebRequest.Create(ftpServer + ftpPath + fi.Name);
			req.Credentials = new NetworkCredential("sasjiali", "yourpassword");
			req.Method = WebRequestMethods.Ftp.UploadFile;
			req.ContentLength = length;
			req.Timeout = 10 * 1000;
			try
			{
				Stream stream = req.GetRequestStream();
				int BufferLength = 2048; //2K
				byte[] b = new byte[BufferLength];
				int i;
				while ((i = fs.Read(b, 0, BufferLength)) > 0)
				{
					stream.Write(b, 0, i);
				}
				stream.Close();
				stream.Dispose();
			}
			catch (Exception e)
			{
				AddLog(1, "FTP创建失败");
				LogRecord.WriteErrorLog("FTP创建失败:" + e.ToString());
				return false;
			}
			finally
			{
				fs.Close();
				req.Abort();
			}
			req.Abort();
			return true;
		}

		//判断文件的目录是否存,不存则创建
		public void FtpCheckDirectoryExist(string destFilePath, string ftpServer, string username, string password)
		{
			string fullDir = FtpParseDirectory(destFilePath);
			string[] dirs = fullDir.Split('/');
			string curDir = "/";
			for (int i = 0; i < dirs.Length; i++)
			{
				string dir = dirs[i];
				//如果是以/开始的路径,第一个为空
				if (dir != null && dir.Length > 0)
				{
					try
					{
						curDir += dir + "/";
						FtpMakeDir(curDir, ftpServer, username, password);
					}
					catch (Exception e)
					{
						AddLog(1, "FTP目录创建失败1！");
						LogRecord.WriteErrorLog("FTP创建目录失败1:" + e.ToString());
					}
				}
			}
		}

		public string FtpParseDirectory(string destFilePath)
		{
			return destFilePath.Substring(0, destFilePath.LastIndexOf("/"));
		}

		//创建目录
		public bool FtpMakeDir(string localFile, string ftpServer, string username, string password)
		{
			FtpWebRequest req = (FtpWebRequest)WebRequest.Create(ftpServer + localFile);
			req.Credentials = new NetworkCredential(username, password);
			req.Method = WebRequestMethods.Ftp.MakeDirectory;
			try
			{
				FtpWebResponse response = (FtpWebResponse)req.GetResponse();
				response.Close();
			}
			catch (Exception e)
			{
				AddLog(1, "FTP目录创建失败2");
				LogRecord.WriteErrorLog("FTP创建目录失败2:" + e.ToString());
				req.Abort();
				return false;
			}
			req.Abort();
			return true;
		}

		#endregion ftp

		#region 控制

		public Thread thread1;
		public Thread thread2;
		public Thread threadInit;

		public void thread1Start()
		{
			//thread1 = new Thread(new ThreadStart(RunPlc1));
			//thread1.IsBackground = true;
			//thread1.Start();
		}

		public void thread2Start()
		{
			//thread2 = new Thread(new ThreadStart(RunPlc2));
			//thread2.IsBackground = true;
			//thread2.Start();
		}

		public void thread1End()
		{
			thread1?.Abort();
		}

		public void thread2End()
		{
			thread2?.Abort();
		}

		#endregion 控制

		#region 通讯硬件初始化

		public void threadInitStart()
		{
			if (threadInit.IsAlive || threadInit != null)
			{
				GlobalVar.Instance.ThreadControl = false;
				threadInit.Abort();
			}
			//主界面 开始 暂停按钮 不激活
			threadInit = new Thread(new ThreadStart(inint_all));
			threadInit.IsBackground = true;
			threadInit.Start();
		}

		private void inint_all()
		{
			if (!GlobalVar.Instance.connectRobot)
			{
				AddLog(1, "机器人未连接！");
				MessageBox.Show("机器人未连接！");
				return;
			}
			var result = h5u.ReadH5U(4232);
			if (result.Message != "11")
			{
				AddLog(1, "机器人不在自动运行中状态！");
				MessageBox.Show("机器人不在自动运行中状态！");
				return;
			}
			//---消除机器人警报
			result = h5u.ReadH5U(4230);
			if (result.Message == "11")
			{
				result = h5u.WriteH5U(4230, "10");
				if (result.IsSuccess)
				{
					AddLog(0, "消除机器人警报");
				}
			}
			GlobalVar.Instance.inintRobot = false;
			TcpServer.Instance.Send("1");
			while (true)
			{
				if (GlobalVar.Instance.inintRobot)
				{
					AddLog(0, "机器人初始化完成");
					break;
				}
				Thread.Sleep(200);
			}

			plc_init();
		}

		private void plc_init()
		{
			var result = h5u.ReadH5U(4092);

			if (result.Message == "11")
			{
				AddLog(0, "收到plc信号 .....初始化");
				//机械手回原

				//给PLC信号 允许PLC初始化
				result = h5u.WriteH5U(4094, "11");
				//等待plc 约1分钟 完成初始化

				if (result.IsSuccess)
				{
					AddLog(0, "等待plc 约1分钟 完成初始化");
				}
			}
			result = h5u.ReadH5U(4096);

			if (result.Message == "11")
			{
				AddLog(0, "plc初始化完成可以设置自动模式");
			}
		}

		#endregion 通讯硬件初始化

		#region 程序开启判断

		public HTuple GetHomMat2D(string path, string str)
		{
			string path_dama = GlobalVar.Instance.CalibrationBasePath + "\\" + path;
			var result_dama = GlobalVar.Instance.calibration.LoadCalibration(path_dama);

			if (!result_dama.IsSuccess)
			{
				return new HTuple();
			}
			else
			{
				return result_dama.Content.HomMat2D;
			}
		}

		public bool IsReadH5u(int d, string dd)
		{
			var result = h5u.ReadH5U(d);
			if (result.Message == dd)
			{
				return true;
			}
			return false;
		}

		public bool RunStart()
		{
			if (string.IsNullOrEmpty(sysConfig.CheckModePath))
			{
				AddLog(1, "请先设置料号程序！");
				MessageBox.Show("请先设置料号程序！");
				return false;
			}
			if (!StaInspect.Instance.Load(sysConfig.CheckModePath))//加载模板
			{
				AddLog(1, "算子加载失败！");
				return false;
			}
			//---- 打码位置变量

			if (StaInspect.Instance.PrjList.Count > 0)
			{
				for (int i = 0; i < StaInspect.Instance.PrjList.Count; i++)
				{
					if (i == 0)
					{
						if (string.IsNullOrEmpty(sysConfig.ModelPrintMappingT1))
						{
							AddLog(1, "搬运1-请设置T面Mapping模板！");
							MessageBox.Show("搬运1-请设T面Mapping模板！");
							return false;
						}
						if (StaInspect.Instance.PrjList[i].IsUseMatrix)
						{
							if (string.IsNullOrEmpty(sysConfig.ModelPrintCodeT1))
							{
								AddLog(1, "搬运1-请设置T面二维码模板！");
								MessageBox.Show("搬运1-请设置T面二维码模板！");
								return false;
							}
						}
						if (StaInspect.Instance.PrjList[i].IsUseLable)
						{
							if (string.IsNullOrEmpty(sysConfig.ModelPrintMingMaT1))
							{
								AddLog(1, "搬运1-请设置T面明码模板！");
								MessageBox.Show("搬运1-请设置T面明码模板！");
								return false;
							}
						}
						if (StaInspect.Instance.PrjList[i].IsUseBadMark)
						{
							if (string.IsNullOrEmpty(sysConfig.ModelPrintBadT1))
							{
								AddLog(1, "搬运1-请设置T面BadMark模板！");
								MessageBox.Show("搬运1-请设置T面BadMark模板！");
								return false;
							}
						}
					}
					if (i == 1)
					{
						if (string.IsNullOrEmpty(sysConfig.ModelPrintMappingT2))
						{
							AddLog(1, "搬运2-请设置T面Mapping模板！");
							MessageBox.Show("搬运2-请设T面Mapping模板！");
							return false;
						}
						if (StaInspect.Instance.PrjList[i].IsUseMatrix)
						{
							if (string.IsNullOrEmpty(sysConfig.ModelPrintCodeT2))
							{
								AddLog(1, "搬运2-请设置T面二维码模板！");
								MessageBox.Show("搬运2-请设置T面二维码模板！");
								return false;
							}
						}
						if (StaInspect.Instance.PrjList[i].IsUseLable)
						{
							if (string.IsNullOrEmpty(sysConfig.ModelPrintMingMaT2))
							{
								AddLog(1, "搬运2-请设置T面明码模板！");
								MessageBox.Show("搬运2-请设置T面明码模板！");
								return false;
							}
						}
						if (StaInspect.Instance.PrjList[i].IsUseBadMark)
						{
							if (string.IsNullOrEmpty(sysConfig.ModelPrintBadT2))
							{
								AddLog(1, "搬运2-请设置T面BadMark模板！");
								MessageBox.Show("搬运2-请设置T面BadMark模板！");
								return false;
							}
						}
					}
				}
			}

			//----
			if (!GlobalVar.Instance.connectRobot)
			{
				AddLog(1, "机器人未连接！");
				MessageBox.Show("请连接机器人再启动！");
				return false;
			}
			if (!GlobalVar.Instance.connectPLC)
			{
				AddLog(1, "PLC未连接！");
				MessageBox.Show("请连接PLC再启动！");
				return false;
			}
			if (!GlobalVar.Instance.connectDuma)
			{
				AddLog(1, "读码器未连接！");
				MessageBox.Show("请连接读码器再启动！");
				return false;
			}
			//if (!GlobalVar.Instance.connectDama)
			//{
			//    AddLog(1, "打码器未连接！");
			//    MessageBox.Show("请连接打码器再启动！");
			//    return;
			//}
			//配方
			if (GlobalVar.Instance.QUDatas.Count < 1)
			{
				AddLog(1, "取料配方未加载！");
				MessageBox.Show("请加载取料配方再启动！");
				return false;
			}
			if (GlobalVar.Instance.OKDatas.Count < 1)
			{
				AddLog(1, "OK料配方未加载！");
				MessageBox.Show("请加载OK料配方再启动！");
				return false;
			}
			if (GlobalVar.Instance.NGDatas.Count < 1)
			{
				AddLog(1, "NG料配方未加载！");
				MessageBox.Show("请加载NG料配方再启动！");
				return false;
			}
			// 加载 打码 标定模板  没有不执行
			//-A面打码

			if (IsReadH5u(4204, "11"))
			{
				GlobalVar.Instance.homMat2D_dama_a1 = GetHomMat2D(sysConfig.GetCoderModelA1, "搬运1-A面");
				if (GlobalVar.Instance.homMat2D_dama_a1 == null)
				{
					MessageBox.Show("请设置搬运1-A面打码标定模板再启动！");
					return false;
				}
				GlobalVar.Instance.homMat2D_dama_a2 = GetHomMat2D(sysConfig.GetCoderModelA2, "搬运2-A面");
				if (GlobalVar.Instance.homMat2D_dama_a2 == null)
				{
					MessageBox.Show("请设置搬运2-A面打码标定模板再启动！");
					return false;
				}
			}
			if (IsReadH5u(4206, "11"))
			{
				GlobalVar.Instance.homMat2D_dama_b1 = GetHomMat2D(sysConfig.GetCoderModelB1, "搬运1-B面");
				if (GlobalVar.Instance.homMat2D_dama_b1 == null)
				{
					MessageBox.Show("请设置搬运1-B面打码标定模板再启动！");
					return false;
				}
				GlobalVar.Instance.homMat2D_dama_b2 = GetHomMat2D(sysConfig.GetCoderModelB2, "搬运2-B面");
				if (GlobalVar.Instance.homMat2D_dama_b2 == null)
				{
					MessageBox.Show("请设置搬运2-B面打码标定模板再启动！");
					return false;
				}
			}
			// 加载标定模板  没有不执行
			string path = GlobalVar.Instance.CalibrationBasePath + "\\" + sysConfig.kacao_1;
			var resultt = GlobalVar.Instance.calibration.LoadCalibration(path);

			if (!resultt.IsSuccess)
			{
				AddLog(1, "取料标定模板加载失败：" + resultt.Message);
				MessageBox.Show("请设置取料标定模板再启动！");
				return false;
			}
			else
			{
				GlobalVar.Instance.homMat2D = resultt.Content.HomMat2D;
				if (GlobalVar.Instance.homMat2D == null)
				{
					AddLog(1, "取料标定模板数据：" + resultt.Message);
					MessageBox.Show("请设置取料标定模板再启动！");
					return false;
				}
			}

			//--- 加载模型
			path = GlobalVar.Instance.ModelBasePath + "\\" + sysConfig.GetModell;
			var result1 = GlobalVar.Instance.shapeModel.LoadShapeModel(path);
			if (result1.IsSuccess)
			{
				GlobalVar.Instance.getMatchParams = result1.Content1;
				if (sysConfig.minScor > 0)
				{
					GlobalVar.Instance.getMatchParams.score = sysConfig.minScor;
				}

				GlobalVar.Instance.getCircleParams = result1.Content2;
				AddLog(0, "物料模板加载成功：" + sysConfig.GetModell);
			}
			else
			{
				AddLog(1, "物料模板加载失败：" + sysConfig.GetModell);
				MessageBox.Show("请设置好物料模板再启动！");
				return false;
			}

			var resullt = h5u.ReadH5U(4006);
			if (resullt.Message != "11")
			{
				AddLog(0, "NG位不允许放料");
				MessageBox.Show("请设置好NG料萃盘再启动！");
				return false;
			}

			// ----  相机设置
			//加载相机列表
			if (!GlobalVar.Instance.connectCamera1)
			{
				GlobalVar.Instance.camera1.LoadCameraList(new List<string>() { sysConfig.GetCamera });
				//打开相机
				var result = GlobalVar.Instance.camera1.OpenCamera();

				if (result[0].IsSuccess)
				{
					AddLog(0, result[0].Message);
					GlobalVar.Instance.connectCamera1 = true;
					//开启采集
					GlobalVar.Instance.camera1.StartGrab();

					//camera.SetGain(sysConfig.GetGain, 0);
					//camera.SetGain(sysConfig.PutGain, 1);
					//camera.SetGain(sysConfig.DownGain, 2);
					GlobalVar.Instance.camera1.SetGain(sysConfig.GetGain, 0);
					//camera.SetExposureTime(sysConfig.GetExposeTime, 0);
				}
				else
				{
					AddLog(1, result[0].Message);
					GlobalVar.Instance.connectCamera1 = false;
				}
			}
			//轨道运行检测
			if (!sysConfig.isRun1 && !sysConfig.isRun2)
			{
				MessageBox.Show("请前往设置选择要运行的轨道!");
				return false;
			}

			// --- 主程序设置
			GlobalVar.Instance.isReadOn = false;
			//plc_fangliao_1();
			GlobalVar.Instance.ThreadControl = true;
			//btn_Start.Enabled = false;
			//btn_Pause.Enabled = true;
			//btn_Stop.Enabled = true;
			//主界面 开始 暂停 停止 按钮激活

			//直接开启后台线程
			return true;
		}

		#endregion 程序开启判断

		#region 主流程

		public string getCoderStr()
		{
			if (sysConfig.chc_coder)
			{
				string str = "";
				if (string.IsNullOrEmpty(sysConfig.dama_model_name) || string.IsNullOrEmpty(sysConfig.dama_user_code) || string.IsNullOrEmpty(sysConfig.dama_pici) || string.IsNullOrEmpty(sysConfig.dama_liushui) || string.IsNullOrEmpty(sysConfig.dama_ver) || string.IsNullOrEmpty(sysConfig.dama_numer_liushui.ToString()))
				{
					AddLog(1, "打码参数不全！");
					return "";
				}
				else
				{
					int m = Convert.ToInt32(sysConfig.dama_liushui);
					m += sysConfig.dama_numer_liushui;
					if (m > 999)
					{
						AddLog(1, "打码流水号超限999！");
						return "";
					}
					int totalLength = 3;
					string mStr = m.ToString().PadLeft(totalLength, '0');
					str = sysConfig.dama_model_name + sysConfig.dama_user_code + sysConfig.dama_pici + mStr + sysConfig.dama_ver;
					sysConfig.dama_liushui = mStr;
				}

				return str;
			}
			else
			{
				long t = (DateTime.Now.ToUniversalTime().Ticks - 621355968000000000) / 10000;
				return t.ToString();
			}
		}

		public void plc_fangliao(int linenum, int d)
		{
			//plc允许放料
			var result = h5u.ReadH5U(d);
			if (result.Message != "11")
			{
				AddLog(0, $"搬运{linenum}-等待取料");
				return;
			}
			else if ((linenum == 1 && GlobalVar.Instance.currplc_step1 == plcStep.请求取料) || (linenum == 2 && GlobalVar.Instance.currplc_step2 == plcStep.请求取料))
			{
				if (GlobalVar.Instance.isPanRun)
				{
					return;
				}

				AddLog(0, $"搬运{linenum}-开始取料");
				TcpServer.Instance.Send("10");
				AddLog(0, $"搬运{linenum}-机器人发送消息:10");
				if (linenum == 1)
				{
					GlobalVar.Instance.TimeStepData1 = new TimeStepData();
					if (GlobalVar.Instance.TimeStepData1.SatrtTime.Year == 1)
					{
						GlobalVar.Instance.TimeStepData1.SatrtTime = DateTime.Now;
					}
					if (GlobalVar.Instance.TimeStepData1.quSatrtTime.Year == 1)
					{
						GlobalVar.Instance.TimeStepData1.quSatrtTime = DateTime.Now;
					}
					GlobalVar.Instance.currplc_step1++;
				}
				else
				{
					GlobalVar.Instance.TimeStepData2 = new TimeStepData();
					if (GlobalVar.Instance.TimeStepData2.SatrtTime.Year == 1)
					{
						GlobalVar.Instance.TimeStepData2.SatrtTime = DateTime.Now;
					}
					if (GlobalVar.Instance.TimeStepData2.quSatrtTime.Year == 1)
					{
						GlobalVar.Instance.TimeStepData2.quSatrtTime = DateTime.Now;
					}
					GlobalVar.Instance.currplc_step2++;
				}
				return;
			}
		}

		public void plc_dama(string facemode, int linenum, OrderData data, CellInfo[] cellInfos, List<ErrList> comInfos, HTuple homMat2D_a, HTuple homMat2D_b, int d)
		{
			//plc A面打码请求
			var result = h5u.ReadH5U(d);
			if (result.Message == "11" || !IsAutoRun)
			{
				AddLog(0, $"搬运{linenum}-{facemode}面打码信号收到");
				// 打码处理
				if (string.IsNullOrEmpty(data.Code))
				{
					data.Code = getCoderStr();
				}
				if (linenum == 1)
				{
					GlobalVar.Instance.currplc_step1++;
					if (GlobalVar.Instance.TimeStepData1 != null)
					{
						if (GlobalVar.Instance.TimeStepData1.printSatrtTime.Year < 2)
						{
							GlobalVar.Instance.TimeStepData1.printSatrtTime = DateTime.Now;
						}
					}
				}
				else
				{
					GlobalVar.Instance.currplc_step2++;
					if (GlobalVar.Instance.TimeStepData1 != null)
						if (GlobalVar.Instance.TimeStepData2.printSatrtTime.Year < 2)
						{
							GlobalVar.Instance.TimeStepData2.printSatrtTime = DateTime.Now;
						}
				}
				PrintCoder(facemode, linenum, data, cellInfos, comInfos, homMat2D_a, homMat2D_b);
			}
		}

		public void plc_duma(string facemode, int linenum, OrderData data, int d1, int d2)
		{
			//plc A /b面扫码请求
			var result = h5u.ReadH5U(d1);
			if (result.Message != "11")
			{
				AddLog(0, $"搬运{linenum}-{facemode}面扫码等待");
				return;
			}
			// 读码处理
			if (linenum == 1)
			{
				if (GlobalVar.Instance.TimeStepData1.readSatrtTime.Year == 1)
				{
					GlobalVar.Instance.TimeStepData1.readSatrtTime = DateTime.Now;
				}
			}
			else
			{
				if (GlobalVar.Instance.TimeStepData2.readSatrtTime.Year == 1)
				{
					GlobalVar.Instance.TimeStepData2.readSatrtTime = DateTime.Now;
				}
			}

			GlobalVar.Instance.dumaCoder = "";
			GlobalVar.Instance.isReadOn = true;

			int i = 0;
			while (GlobalVar.Instance.isReadOn)
			{
				if (!GlobalVar.Instance.ThreadControl)
				{
					break;
				}
				if (i > sysConfig.numer_duma_time)
				{
					GlobalVar.Instance.isReadWarn = true;
					data.IsBaoFei = true;
					MySqlHelper.Add_Record("报警", "读码超时", GlobalVar.Instance.sysAdmins.LoginName, "1");
					AddLog(0, "搬运1-读码-读码超时报警处理");
					break;
				}
				if (!string.IsNullOrEmpty(GlobalVar.Instance.dumaCoder))
				{
					AddLog(0, $"搬运{linenum}读码" + GlobalVar.Instance.dumaCoder);

					if (linenum == 1)
					{
						GlobalVar.Instance.OrderData1.Code = GlobalVar.Instance.dumaCoder;
						if (sysConfig.mapping_duma)
						{
							string text = GlobalVar.Instance.GetEditMapping(sysConfig, GlobalVar.Instance.cellInfos_1, GlobalVar.Instance.OrderData1);
							LogRecord.WriteMapping($"{StaInspect.Instance.loadPath}\\mapping", GlobalVar.Instance.OrderData1.Code, text);
							AddLog(0, $"搬运{linenum}-写入mapping文件{GlobalVar.Instance.OrderData1.Code}.txt完成,路径：{StaInspect.Instance.loadPath}\\mapping");
						}

						//doMapping(GlobalVar.Instance.cellInfos_1, GlobalVar.Instance.comInfos_1, GlobalVar.Instance.OrderData1, GlobalVar.Instance.OrderData1.Code);
					}
					else
					{
						GlobalVar.Instance.OrderData2.Code = GlobalVar.Instance.dumaCoder;
						if (sysConfig.mapping_duma)
						{
							string text = GlobalVar.Instance.GetEditMapping(sysConfig, GlobalVar.Instance.cellInfos_2, GlobalVar.Instance.OrderData2);
							LogRecord.WriteMapping($"{StaInspect.Instance.loadPath}\\mapping", GlobalVar.Instance.OrderData2.Code, text);
							AddLog(0, $"搬运{linenum}-写入mapping文件{GlobalVar.Instance.OrderData2.Code}.txt完成,路径：{StaInspect.Instance.loadPath}\\mapping");
						}

						//doMapping(GlobalVar.Instance.cellInfos_2, GlobalVar.Instance.comInfos_2, GlobalVar.Instance.OrderData2, GlobalVar.Instance.OrderData2.Code);
					}

					string po_path = StaInspect.Instance.loadPath + "\\Savemap\\板号-" + GlobalVar.Instance.dumaCoder;
					try
					{
						// 确保code文件夹存在
						if (Directory.Exists(data.path))
						{
							// 确保新的文件夹名不存在
							if (Directory.Exists(po_path))
							{
								Directory.Delete(po_path);
							}
							Microsoft.VisualBasic.FileIO.FileSystem.RenameDirectory(data.path, "板号-" + GlobalVar.Instance.dumaCoder);
						}
					}
					catch (Exception ex)
					{
						Console.WriteLine("发生错误：" + ex.Message);
						break;
					}

					GlobalVar.Instance.isReadOn = false;
					break;
				}
				else
				{
					AddLog(0, $"搬运{linenum}-{facemode}面等待读码");
				}
				i++;
				Thread.Sleep(1000);
			}

			//扫码A/B面完成给信号
			result = h5u.WriteH5U(d2, "11");//扫码完成给信号
			if (!result.IsSuccess)
			{
				AddLog(1, $"搬运{linenum}-{facemode}面读码失败!");
			}
			else
			{
				if (linenum == 1)
				{
					GlobalVar.Instance.currplc_step1++;
				}
				else
				{
					GlobalVar.Instance.currplc_step2++;
				}
				AddLog(0, $"搬运{linenum}-{facemode}面读码完成!");
				AddLog(0, $"搬运{linenum}-{facemode}读码结果:" + GlobalVar.Instance.dumaCoder);
			}
		}

		public void plc_xialiao(int linenum, OrderData data, int d1, int d2)
		{
			var result = h5u.ReadH5U(d1);
			if (result.Message != "11")
			{
				AddLog(0, $"搬运{linenum}-等待下料");
				return;
			}
			else if ((linenum == 1 && GlobalVar.Instance.currplc_step1 == plcStep.下料) || (linenum == 2 && GlobalVar.Instance.currplc_step2 == plcStep.下料))
			{
				if (GlobalVar.Instance.isPanRun)
				{
					return;
				}
				TcpServer.Instance.Send(d2.ToString());
				if (linenum == 1)
				{
					GlobalVar.Instance.currplc_step1++;
				}
				else
				{
					GlobalVar.Instance.currplc_step2++;
				}
				return;
			}
		}

		#endregion 主流程

		#region 检测

		//检测模式 MODEL初始化
		public void selectedModeChanged()
		{
			var result = h5u.ReadH5U(4200);
			string m_str = "";
			if (result.Message == "11")
			{
				m_str += "A";
			}
			result = h5u.ReadH5U(4202);
			if (result.Message == "11")
			{
				m_str += "B";
			}
			switch (m_str)
			{
				case "A":
					StaInspect.Instance.Mode = WorkMode.OA;
					break;

				case "B":
					StaInspect.Instance.Mode = WorkMode.OB;
					break;

				case "AB":
					StaInspect.Instance.Mode = WorkMode.AB;
					break;

				default:
					break;
			}
		}

		#endregion 检测

		#region 读码打码

		private void OnTCPReadRecive(object sender, string e)
		{
			string msg = e.ToString();
			if (msg.IndexOf("1,") > -1)
			{
				AddLog(0, $"读码器异常");
			}
			else
			{
				if (msg.IndexOf("0,") > -1)
				{
					if (msg.IndexOf(',') > -1)
					{
						if (GlobalVar.Instance.isReadOn)
						{
							var pos = msg.Split(',');
							GlobalVar.Instance.dumaCoder = pos[1];
							AddLog(0, $"{GlobalVar.Instance.dumaStr}-读码信息：{pos[1]}");
							if (!IsAutoRun)
							{
								DoOneMsg($"0,{GlobalVar.Instance.dumaStr}-读码器信息：{pos[1]}");
							}
						}
					}
				}
			}
		}

		public void OnTCPPrintRecive(object sender, string e)
		{
			Console.WriteLine($"111收到：{e.ToString()}");
			string msg = e.ToString().Trim();
			//TcpRecive.Print.sendMsg($"L: + {pos[0]},{xx},{yy},{r}");
			if (GlobalVar.Instance.damaMode == "map")
			{
				if (msg.IndexOf("LS") > -1)
				{
					TcpRecive.Print.sendMsg("P:CODE:" + GlobalVar.Instance.damaStr);
					AddLog(0, GlobalVar.Instance.damaStr);
				}
			}
			else
			{
				if (GlobalVar.Instance.damaStr.IndexOf("+") > -1)
				{
					var pos = GlobalVar.Instance.damaStr.Split('+');
					if (msg.IndexOf("LS") > -1)
					{
						TcpRecive.Print.sendMsg("D:CODE:" + pos[0]);
						AddLog(0, "打码内容:" + pos[0]);
					}
					if (msg.IndexOf("DS") > -1)
					{
						TcpRecive.Print.sendMsg("P:CODE:" + pos[1]);
						AddLog(0, "打码位置" + pos[1]);
					}
				}
			}

			if (msg.IndexOf("PS") > -1)
			{
				TcpRecive.Print.sendMsg("MB");
				AddLog(0, "开始打码");
			}

			if (msg.IndexOf("ME") > -1)
			{
				GlobalVar.Instance.dama_ison = true;
				if (GlobalVar.Instance.damaMode == "map")
				{
					AddLog(0, "打点完成");
				}
				else
				{
					AddLog(0, "打码完成");
				}
			}
		}

		public string selectedPrintModeChanged()
		{
			var result = h5u.ReadH5U(4204);
			string m_str = "";
			if (result.Message == "11")
			{
				m_str += "A";
			}
			result = h5u.ReadH5U(4206);
			if (result.Message == "11")
			{
				m_str += "B";
			}
			return m_str;
		}

		public void PrintCoder(string facemode, int linenum, OrderData data, CellInfo[] cellInfos, List<ErrList> comInfos, HTuple homMat2D_a, HTuple homMat2D_b)
		{
			string printMode = selectedPrintModeChanged();
			int ppp = sysConfig.numer_check_col * sysConfig.numer_check_row;
			ppp--;
			if (cellInfos == null)
			{
				if (linenum == 1)
				{
					GlobalVar.Instance.currplc_step1++;
				}
				else
				{
					GlobalVar.Instance.currplc_step2++;
				}
				AddLog(0, $"搬运{linenum}-没有检测数据！不能打点！");
				return;
			}
			if (facemode == "A")
			{
				if ((StaInspect.Instance.Mode == WorkMode.OB))
				{
					if (linenum == 1)
					{
						GlobalVar.Instance.currplc_step1++;
					}
					else
					{
						GlobalVar.Instance.currplc_step2++;
					}
					AddLog(0, $"打码-搬运{linenum}-触摸屏选择不检测-A面");
					return;
				}

				if ((printMode == "B"))
				{
					if (linenum == 1)
					{
						GlobalVar.Instance.currplc_step1++;
					}
					else
					{
						GlobalVar.Instance.currplc_step2++;
					}
					AddLog(0, $"打码-搬运{linenum}-触摸屏选择不打点-A面");
					return;
				}

				if (data.IsBaoFei)
				{
					if (linenum == 1)
					{
						GlobalVar.Instance.currplc_step1++;
					}
					else
					{
						GlobalVar.Instance.currplc_step2++;
					}
					AddLog(0, $"打码-搬运{linenum}-检测报废不打点-A面");
					return;
				}

				//---- 同步打码 + B面同步到A面打点-A面正常打点
				if ((sysConfig.dama_tongbu) || (sysConfig.dama_btoa))
				{
					if (sysConfig.dama_domappingA)
					{
						for (int i = 0; i < cellInfos.Length; i++)
						{
							if (i > ppp)
							{
								break;
							}
							Console.WriteLine("序号" + i + "----A面-坐标：" + cellInfos[i].DicCell["A"].RealPos + ",状态" + cellInfos[i].DicCell["A"].Status);
							//",B面坐标："+ item.DicCell["B"].RealPos+"状态"+ item.DicCell["B"].Status
							if (cellInfos[i].IsNG)
							{
								dama_dadian_p(homMat2D_a, cellInfos[i].DicCell["A"].RealPos.X.ToString(), cellInfos[i].DicCell["A"].RealPos.Y.ToString(), "0", linenum, facemode);
								Thread.Sleep(100);
							}

							if (!GlobalVar.Instance.ThreadControl)
							{
								return;
							}
						}
					}
				}
				//---- 分别打码
				if (sysConfig.dama_fenbie && sysConfig.dama_domappingA)
				{
					for (int i = 0; i < cellInfos.Length; i++)
					{
						if (i > ppp)
						{
							break;
						}
						Console.WriteLine("序号" + i + "----A面-坐标：" + cellInfos[i].DicCell["A"].RealPos + ",状态" + cellInfos[i].DicCell["A"].Status);
						//",B面坐标："+ item.DicCell["B"].RealPos+"状态"+ item.DicCell["B"].Status
						if (cellInfos[i].DicCell["A"].Status == CellStatus.NG)
						{
							dama_dadian_p(homMat2D_a, cellInfos[i].DicCell["A"].RealPos.X.ToString(), cellInfos[i].DicCell["A"].RealPos.Y.ToString(), "0", linenum, facemode);
							Thread.Sleep(100);
						}
						if (!GlobalVar.Instance.ThreadControl)
						{
							return;
						}
					}
				}
				AddLog(0, $"打码-搬运{linenum}-A面打点完成");
				//----判断是否打码
				if (comInfos.Count > 0)
				{
					if (comInfos[0].MatrixComponents.Count > 0)
					{
						AddLog(0, $"打码-搬运{linenum}-A面打码...");
						data.BadMark = GetBadMArkCount(cellInfos);
						dama_dama_p(homMat2D_a, comInfos[0].MatrixComponents, data, "0", linenum, facemode);
						AddLog(0, $"打码-搬运{linenum}-A面打码完成");
					}
				}

				if (linenum == 1)
				{
					GlobalVar.Instance.currplc_step1++;
				}
				else
				{
					GlobalVar.Instance.currplc_step2++;
				}
			}
			else
			{
				if ((StaInspect.Instance.Mode == WorkMode.OA))
				{
					if (linenum == 1)
					{
						GlobalVar.Instance.currplc_step1++;
					}
					else
					{
						GlobalVar.Instance.currplc_step2++;
					}
					AddLog(0, $"打码-搬运{linenum}-触摸屏选择不检测-B面");
					return;
				}

				if ((printMode == "A"))
				{
					if (linenum == 1)
					{
						GlobalVar.Instance.currplc_step1++;
					}
					else
					{
						GlobalVar.Instance.currplc_step2++;
					}
					AddLog(0, $"打码-搬运{linenum}-触摸屏选择不打点-B面");
					return;
				}

				if (data.IsBaoFei)
				{
					if (linenum == 1)
					{
						GlobalVar.Instance.currplc_step1++;
					}
					else
					{
						GlobalVar.Instance.currplc_step2++;
					}
					AddLog(0, $"打码-搬运{linenum}-检测报废不打点-B面");
					return;
				}
				//---- 同步打码 + B面同步到A面打点-A面正常打点

				if ((sysConfig.dama_tongbu) && sysConfig.dama_domappingB)
				{
					for (int i = 0; i < cellInfos.Length; i++)
					{
						if (i > ppp)
						{
							break;
						}
						//Console.WriteLine("序号" + i + "----B面-坐标：" +  cellInfos[i].DicCell["B"].RealPos + ",状态" +  cellInfos[i].DicCell["B"].Status);
						//",B面坐标："+ item.DicCell["B"].RealPos+"状态"+ item.DicCell["B"].Status
						if (cellInfos[i].IsNG)
						{
							dama_dadian_p(homMat2D_b, cellInfos[i].DicCell["B"].RealPos.X.ToString(), cellInfos[i].DicCell["B"].RealPos.Y.ToString(), "0", linenum, facemode);
							Thread.Sleep(10);
						}
						if (!GlobalVar.Instance.ThreadControl)
						{
							return;
						}
					}
				}
				//---- 分别打码
				if (sysConfig.dama_fenbie && sysConfig.dama_domappingB)
				{
					for (int i = 0; i < cellInfos.Length; i++)
					{
						if (i > ppp)
						{
							break;
						}
						//Console.WriteLine("序号" + i + "----B面-坐标：" +  cellInfos[i].DicCell["B"].RealPos + ",状态" +  cellInfos[i].DicCell["B"].Status);
						//",B面坐标："+ item.DicCell["B"].RealPos+"状态"+ item.DicCell["B"].Status
						if (cellInfos[i].DicCell["B"].Status == CellStatus.NG)
						{
							dama_dadian_p(homMat2D_b, cellInfos[i].DicCell["B"].RealPos.X.ToString(), cellInfos[i].DicCell["B"].RealPos.Y.ToString(), "0", linenum, facemode);
							Thread.Sleep(100);
						}
						if (!GlobalVar.Instance.ThreadControl)
						{
							return;
						}
					}
				}

				//----判断是否打码
				if (sysConfig.dama_docoderB)
				{
					if (StaInspect.Instance.Mode == WorkMode.OB)
					{
						if (comInfos.Count > 0)
						{
							if (comInfos[0].MatrixComponents.Count > 0)
							{
								AddLog(0, $"打码-搬运{linenum}-B面打码...");
								data.BadMark = GetBadMArkCount(cellInfos);
								dama_dama_p(homMat2D_b, comInfos[0].MatrixComponents, data, "0", linenum, facemode);
								AddLog(0, $"打码-搬运{linenum}-B面打码完成");
							}
						}
					}
					if (StaInspect.Instance.Mode == WorkMode.AB)
					{
						if (comInfos.Count > 1)
						{
							if (comInfos[1].MatrixComponents.Count > 0)
							{
								AddLog(0, $"打码-搬运{linenum}-B面打码...");
								data.BadMark = GetBadMArkCount(cellInfos);
								dama_dama_p(homMat2D_b, comInfos[1].MatrixComponents, data, "0", linenum, facemode);
								AddLog(0, $"打码-搬运{linenum}-B面打码完成");
							}
						}
					}
				}
				if (linenum == 1)
				{
					GlobalVar.Instance.currplc_step1++;
				}
				else
				{
					GlobalVar.Instance.currplc_step2++;
				}
				AddLog(0, $"打码-搬运{linenum}-B面打点完成");
			}
		}

		public void dama_dadian_p(HTuple mmm, string x, string y, string r, int linenum, string facemode)
		{
			try
			{
				float imageX;
				float imageY;
				imageX = Convert.ToSingle(x);
				imageY = Convert.ToSingle(y);
				AddLog(0, "检测坐标：" + "x:" + imageX + ",y:" + imageY);
				//仿射变换，获取物理坐标

				HOperatorSet.AffineTransPoint2d(mmm, imageX, imageY, out HTuple posX, out HTuple posY);
				float xx, yy;
				//string xx = Convert.ToSingle(posX.D).ToString();
				//string yy = Convert.ToSingle(posY.D).ToString();
				//计算物料吸取坐标
				xx = Convert.ToSingle(posX.D);
				yy = Convert.ToSingle(posY.D);

				AddLog(0, $"打码坐标：" + "x:" + xx + ",y:" + yy);

				GlobalVar.Instance.dama_ison = false;
				string[] pos;
				GlobalVar.Instance.damaMode = "map";
				if (facemode == "A")
				{
					if (linenum == 1)
					{
						pos = sysConfig.ModelPrintMappingT1.Split('.');
					}
					else
					{
						pos = sysConfig.ModelPrintMappingT2.Split('.');
					}
				}
				else
				{
					if (linenum == 1)
					{
						pos = sysConfig.ModelPrintMappingB1.Split('.');
					}
					else
					{
						pos = sysConfig.ModelPrintMappingB2.Split('.');
					}
				}
				GlobalVar.Instance.damaStr = $"{xx},{yy},{r}";
				TcpRecive.Print.sendMsg($"L:{pos[0]}");
				AddLog(0, facemode + " L:" + pos[0]);

				while (GlobalVar.Instance.ThreadControl)
				{
					if (GlobalVar.Instance.dama_ison)
					{
						AddLog(0, "打点成功");
						break;
					}
				}
			}
			catch (Exception)
			{
				GlobalVar.Instance.ThreadControl = false;
				MessageBox.Show("插件异常，请重启软件！");
			}
		}

		public void dama_dama_p(HTuple mmm, List<ErrComponent> ttlist, OrderData data, string r, int linenum, string facemode)
		{
			double a;
			string models1 = "";
			string models2 = "";
			string models3 = "";
			a = Math.Round(StaInspect.Instance.codeAngle + 1, 3);
			if (facemode == "A")
			{
				if (linenum == 1)
				{
					var pos = sysConfig.ModelPrintBadT1.Split('.');
					models1 = pos[0];
					pos = sysConfig.ModelPrintCodeT1.Split('.');
					models2 = pos[0];
					pos = sysConfig.ModelPrintMingMaT1.Split('.');
					models3 = pos[0];
				}
				else
				{
					var pos = sysConfig.ModelPrintBadT2.Split('.');
					models1 = pos[0];
					pos = sysConfig.ModelPrintCodeT2.Split('.');
					models2 = pos[0];
					pos = sysConfig.ModelPrintMingMaT2.Split('.');
					models3 = pos[0];
				}
			}
			else
			{
				if (linenum == 1)
				{
					var pos = sysConfig.ModelPrintBadB1.Split('.');
					models1 = pos[0];
					pos = sysConfig.ModelPrintCodeB1.Split('.');
					models2 = pos[0];
					pos = sysConfig.ModelPrintMingMaB1.Split('.');
					models3 = pos[0];
				}
				else
				{
					var pos = sysConfig.ModelPrintBadB2.Split('.');
					models1 = pos[0];
					pos = sysConfig.ModelPrintCodeB2.Split('.');
					models2 = pos[0];
					pos = sysConfig.ModelPrintMingMaB2.Split('.');
					models3 = pos[0];
					AddLog(0, "B面打码开启----" + models1 + "," + models2 + "," + models3);
				}
			}

			AddLog(0, models1 + "," + models2 + "," + models3);

			foreach (var item in ttlist)
			{
				if (item.Lib.IsBadMarkPos && sysConfig.dama_dobadmark && (facemode == "A"))
				{
					if (data.BadMark > 0)
					{
						GlobalVar.Instance.damaMode = "bad";
						dama_dama_p_p(mmm, item.CenterPoint.X.ToString(), item.CenterPoint.Y.ToString(), models1, data.BadMark.ToString(), 0, "0", "BadMark");
					}
				}
				if ((item.Lib.IsMatrixPos && sysConfig.dama_docoder && (facemode == "A")) || (sysConfig.dama_docoderB && (facemode == "B")))
				{
					//if (StaInspect.Instance.codeAngle > 0)
					//{
					//    a = Math.Round(StaInspect.Instance.codeAngle - 1, 3);
					//}
					//else
					//{
					//    a = Math.Round(StaInspect.Instance.codeAngle + 1, 3);
					//}
					AddLog(0, $"code增加补偿 x:{(float)data.codex} y:{(float)data.codey}");
					AddLog(0, $"B面打码开启----code增加补偿 x:{(float)data.codex} y:{(float)data.codey}");
					GlobalVar.Instance.damaMode = "er";
					dama_dama_p_p(mmm, (item.CenterPoint.X + (float)data.codex).ToString(), (item.CenterPoint.Y + (float)data.codey).ToString(), models2, data.Code, 0, a.ToString(), "二维码");
				}
				if (item.Lib.IsLablePos && sysConfig.dama_domingma)
				{
					GlobalVar.Instance.damaMode = "ming";
					a = Math.Round(StaInspect.Instance.codeAngle, 3);
					dama_dama_p_p(mmm, item.CenterPoint.X.ToString(), item.CenterPoint.Y.ToString(), models3, data.Code, 0, a.ToString(), "明码");
				}
			}
		}

		public void dama_dama_p_p(HTuple mmm, string X, string Y, string models, string code, int badmark, string r, string log)
		{
			try
			{
				float imageX;
				float imageY;
				imageX = Convert.ToSingle(X);
				imageY = Convert.ToSingle(Y);
				AddLog(0, "检测坐标：" + "x:" + imageX + ",y:" + imageY);
				//仿射变换，获取物理坐标
				HOperatorSet.AffineTransPoint2d(mmm, imageX, imageY, out HTuple posX1, out HTuple posY1);
				float xx, yy;
				xx = Convert.ToSingle(posX1.D);
				yy = Convert.ToSingle(posY1.D);

				AddLog(0, log + "坐标：" + "x:" + xx + ",y:" + yy);

				GlobalVar.Instance.dama_ison = false;
				//---明码
				//dama_send_cmd1("L:" + models, code, xx.ToString(), yy.ToString(), r);
				GlobalVar.Instance.damaStr = $"{code}+{xx},{yy},{r}";
				TcpRecive.Print.sendMsg($"L:{models}");
				while (GlobalVar.Instance.ThreadControl)
				{
					if (GlobalVar.Instance.dama_ison)
					{
						AddLog(0, $"打码-" + log + "成功");
						break;
					}
				}
			}
			catch (Exception)
			{
				GlobalVar.Instance.ThreadControl = false;
				MessageBox.Show("插件异常，请重启软件！");
			}
		}

		public bool IsDoNGMax(CellInfo[] cellInfos)
		{
			try
			{
				if (cellInfos == null)
				{
					return false;
				}

				if (cellInfos.Length < 0)
				{
					return false;
				}
				int g = 0;
				int ppp = sysConfig.numer_check_col * sysConfig.numer_check_row;
				if (cellInfos.Length > 0)
				{
					for (int i = 0; i < cellInfos.Length; i++)
					{
						if (i >= ppp)
						{
							break;
						}
						else
						{
							int m = (i + 1) % sysConfig.numer_check_col;
							if (cellInfos[i].IsNG)
							{
								g++;
							}
						}
					}
				}

				if (sysConfig.chc_ng)
				{
					if (g >= sysConfig.ngCount)
					{
						return true;
					}
				}

				return false;
			}
			catch (Exception)
			{
				return false;
			}
		}

		/// <summary>
		///
		/// </summary>
		/// <param name="cellInfos"></param>
		/// <param name="comInfos"></param>
		/// <param name="data"></param>
		/// <param name="ss"></param>
		/// <param name="tempCode"></param>
		public void doMapping(CellInfo[] cellInfos, List<ErrList> comInfos, OrderData data, string ss, string tempCode = "")
		{
			//第一行：Stirip ID，与文件名、二维码、明码一致；
			//第二行：Manufafacturer P/ N, 供应商基板型号；
			//第三行：Customer P/ N, 客户基板型号；
			//第四行：Row , Col，行 列式数；
			//第五行：GOOD UNIT，合格数量；
			//第六行：空
			//第七行：此行 开始为实际 2D MAPING 图

			if (sysConfig.mapping_donot)
			{
				return;
			}
			try
			{
				if (cellInfos == null)
				{
					AddLog(0, "检测-无数据!");
					return;
				}

				if (cellInfos.Length < 0)
				{
					AddLog(0, "检测-数据不存在!");
					return;
				}
				string code;
				if (sysConfig.mapping_duma)
				{
					data.Code = tempCode;
					code = data.Code;
					AddLog(0, $"搬运{ss}-读码-mapping-生成流水号:{code}");
				}
				else
				{
					if (string.IsNullOrEmpty(data.Code))
					{
						if (data.IsBaoFei)
						{
							code = DateTime.Now.ToString("yyyy-MM-dd HH∶mm∶ss");
						}
						else
						{
							data.Code = getCoderStr();
							code = data.Code;
							AddLog(0, $"搬运{ss}-mapping-生成流水号:{code}");
						}
					}
					else
					{
						code = data.Code;
					}
				}

				string timeStr = DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss");

				// mapping
				int g = 0;
				int f = 0;
				int okA = 0;
				int okB = 0;
				int ngA = 0;
				int ngB = 0;
				int aones = 0;
				int atwos = 0;
				int bones = 0;
				int btwos = 0;
				string str_cell = "";
				int ppp = sysConfig.numer_check_col * sysConfig.numer_check_row;
				if (!string.IsNullOrEmpty(code))
				{
					string str;
					if (cellInfos.Length > 0)
					{
						for (int i = 0; i < cellInfos.Length; i++)
						{
							if (i >= ppp)
							{
								break;
							}
							else
							{
								int m = (i + 1) % sysConfig.numer_check_col;
								if (cellInfos[i].IsNG)
								{
									str_cell += "0";
									g++;
								}
								else
								{
									str_cell += "1";
								}
								if (m == 0)
								{
									str_cell += "\n";
								}
								if (cellInfos[i].DicCell.ContainsKey("A"))
								{
									if (cellInfos[i].DicCell["A"].Status == CellStatus.NG)
									{
										ngA++;
									}

									if (cellInfos[i].DicCell["A"].Status == CellStatus.PASS)
									{
										aones++;
										okA++;
									}

									if (cellInfos[i].DicCell["A"].Status == CellStatus.OK)
									{
										atwos++;
										okA++;
									}
								}

								if (cellInfos[i].DicCell.ContainsKey("B"))
								{
									if (cellInfos[i].DicCell["B"].Status == CellStatus.NG)
									{
										ngB++;
									}

									if (cellInfos[i].DicCell["B"].Status == CellStatus.PASS)
									{
										bones++;
										okB++;
									}

									if (cellInfos[i].DicCell["B"].Status == CellStatus.OK)
									{
										btwos++;
										okB++;
									}
								}
							}
						}
					}
					if (sysConfig.chc_mapping)
					{
						string text = GlobalVar.Instance.GetEditMapping(sysConfig, cellInfos, data);
						if (!string.IsNullOrEmpty(sysConfig.dama_pici))
						{
							Directory.CreateDirectory($"{StaInspect.Instance.loadPath}\\mapping\\{sysConfig.dama_pici}");
							LogRecord.WriteMapping($"{StaInspect.Instance.loadPath}\\mapping\\{sysConfig.dama_pici}", code, text);
							AddLog(0, $"搬运{ss}-写入mapping文件{code}.txt完成,路径：{StaInspect.Instance.loadPath}\\mapping");
						}
						else
						{
							Directory.CreateDirectory($"{StaInspect.Instance.loadPath}\\mapping");
							LogRecord.WriteMapping($"{StaInspect.Instance.loadPath}\\mapping", code, text);
							AddLog(0, $"搬运{ss}-写入mapping文件{code}.txt完成,路径：{StaInspect.Instance.loadPath}\\mapping");
						}
					}
					else
					{
						//---- 组合mapping
						str = "Strip_ID：" + data.Code + "\n";
						f = ppp - g;
						str += "Manufafacturer P/N：" + sysConfig.txt_gong_type + "\n";
						str += "Customer P/N：" + sysConfig.txt_ke_type + "\n";
						str += "Row = " + sysConfig.numer_check_col + "；Col = " + sysConfig.numer_check_row + "\n";
						str += "GOOD UNIT : " + f.ToString() + "\n\n";
						str += str_cell;

						if (!string.IsNullOrEmpty(sysConfig.dama_pici))
						{
							Directory.CreateDirectory($"{StaInspect.Instance.loadPath}\\mapping\\{sysConfig.dama_pici}");
							LogRecord.WriteMapping($"{StaInspect.Instance.loadPath}\\mapping\\{sysConfig.dama_pici}", code, str);
							AddLog(0, $"搬运{ss}-写入mapping文件{code}.txt完成,路径：{StaInspect.Instance.loadPath}\\mapping\\{sysConfig.dama_pici}");
						}
						else
						{
							Directory.CreateDirectory($"{StaInspect.Instance.loadPath}\\mapping");
							LogRecord.WriteMapping($"{StaInspect.Instance.loadPath}\\mapping", code, str);
							AddLog(0, $"搬运{ss}-写入mapping文件{code}.txt完成,路径：{StaInspect.Instance.loadPath}\\mapping");
						}

						if (sysConfig.isFTP)
						{
							//bool mmm = FtpUpload(StaInspect.Instance.loadPath + "\\mapping\\" + data.Code + ".txt", sysConfig.mes_ftp_ip, sysConfig.mes_ftp_user, sysConfig.mes_ftp_password, sysConfig.mes_ftp_path);
							//if (mmm)
							//{
							//    AddLog(0, $"搬运{ss}-mapping上传成功");
							//    LogRecord.WriteOperLog(StaInspect.Instance.loadPath + "\\mapping\\" + data.Code + ".txt" + $"搬运{ss}-mapping上传成功");
							//}
							//else
							//{
							//    AddLog(1, $"搬运{ss}-mapping上传失败");
							//    LogRecord.WriteOperLog(StaInspect.Instance.loadPath + "\\mapping\\" + data.Code + ".txt" + $"搬运{ss}-mapping上传失败");
							//}
						}
					}
				}
				//-- cellinfo数据
				if (comInfos.Count > 0)
				{
					foreach (var item in comInfos)
					{
						if (item.mapInfos.Count > 0)
						{
							List<CellInfoDetail> detailList = new List<CellInfoDetail>();

							foreach (var gg in item.mapInfos)
							{
								gg.lotid = code;
								gg.lineid = Convert.ToInt32(ss);
								if (StaInspect.Instance.Mode == WorkMode.OA)
								{
									gg.workmode = "A";
								}
								if (StaInspect.Instance.Mode == WorkMode.OB)
								{
									gg.workmode = "B";
								}
								if (StaInspect.Instance.Mode == WorkMode.AB)
								{
									gg.workmode = "AB";
								}

								detailList.Add(new CellInfoDetail()
								{
									cellid = gg.cellid,
									damaPici = sysConfig.dama_pici,
									damaVer = sysConfig.dama_ver,
									facename = gg.facename,
									img = gg.img,
									imgcenter = gg.imgcenter,
									lineid = gg.lineid,
									liuShui = "",
									state = gg.state,
									lotid = gg.lotid,
									modelName = sysConfig.dama_model_name,
									userCode = sysConfig.dama_user_code,
									workmode = gg.workmode,
									time = gg.time,
									rectErrs = gg.rectErrs
								});
							}
							if (MySqlHelper.Add_CellInfo(item.mapInfos, timeStr))
							{
								AddLog(0, $"搬运{ss}- cellinfo-{StaInspect.Instance.Mode}-上传数据库成功");

								//Add_CellInfoDetail
								MySqlHelper.Add_CellInfoDetail(detailList, timeStr);
							}
							else
							{
								AddLog(0, $"搬运{ss}- cellinfo-{StaInspect.Instance.Mode}-上传数据库失败");
							}
						}
					}
				}
				//增加量产---
				if (data.IsBaoFei)
				{
					return;
				}
				List<product> product = new List<product>();
				string workmode = "";
				product productOne = new product();
				if (StaInspect.Instance.Mode == WorkMode.OA)
				{
					workmode = "A";
				}
				if (StaInspect.Instance.Mode == WorkMode.OB)
				{
					workmode = "B";
				}
				if (StaInspect.Instance.Mode == WorkMode.AB)
				{
					workmode = "AB";
				}
				productOne.aones = aones;
				productOne.atwos = atwos;
				productOne.bones = bones;
				productOne.btwos = btwos;

				productOne.lotid = data.Code;
				productOne.ispass = data.IsPass ? 1 : 0;
				productOne.ng = g;
				productOne.ok = ppp - g;
				productOne.time = timeStr;
				productOne.total = ppp;
				productOne.workmode = workmode;
				productOne.okA = okA;
				productOne.ngA = ngA;
				productOne.okB = okB;
				productOne.ngB = ngB;
				productOne.state = 1;

				product.Add(productOne);

				#region 存储明细，确保正常之后，可以修改明细改成产品表

				List<ProductDetail> listProduct = new List<ProductDetail>();

				ProductDetail productdetail = new ProductDetail();

				productdetail.aones = productOne.aones;
				productdetail.atwos = productOne.atwos;
				productdetail.bones = productOne.bones;
				productdetail.btwos = productOne.btwos;

				productdetail.lotid = productOne.lotid;
				productdetail.ispass = productOne.ispass;
				productdetail.ng = productOne.ng;
				productdetail.ok = productOne.ok;
				productdetail.time = productOne.time;
				productdetail.total = productOne.total;
				productdetail.workmode = productOne.workmode;
				productdetail.okA = productOne.okA;
				productdetail.ngA = productOne.ngA;
				productdetail.okB = productOne.okB;
				productdetail.ngB = productOne.ngB;
				productdetail.state = 1;
				productdetail.modelName = sysConfig.dama_model_name;
				productdetail.userCode = sysConfig.dama_user_code;
				productdetail.damaPici = sysConfig.dama_pici;
				productdetail.liuShui = "";
				productdetail.damaVer = sysConfig.dama_ver;
				listProduct.Add(productdetail);

				#endregion 存储明细，确保正常之后，可以修改明细改成产品表

				if (MySqlHelper.Add_Product(product))
				{
					AddLog(0, $"搬运{ss}-上传product数据库成功");

					// 保存明细
					MySqlHelper.Add_Product_Detail(listProduct);
				}
				else
				{
					AddLog(1, $"搬运{ss}-上传product数据库失败");
				}
			}
			catch (Exception)
			{
			}
		}

		public int GetBadMArkCount(CellInfo[] cellInfos)
		{
			//第一行：Stirip ID，与文件名、二维码、明码一致；
			//第二行：Manufafacturer P/ N, 供应商基板型号；
			//第三行：Customer P/ N, 客户基板型号；
			//第四行：Row , Col，行 列式数；
			//第五行：GOOD UNIT，合格数量；
			//第六行：空
			//第七行：此行 开始为实际 2D MAPING 图
			int g = 0;
			string str_cell = "";
			int ppp = sysConfig.numer_check_col * sysConfig.numer_check_row;
			if (cellInfos.Length > 0)
			{
				for (int i = 0; i < cellInfos.Length; i++)
				{
					if (i >= ppp)
					{
						break;
					}
					else
					{
						int m = (i + 1) % sysConfig.numer_check_col;
						if (cellInfos[i].IsNG)
						{
							str_cell += "0";
							g++;
						}
						else
						{
							str_cell += "1";
						}
						if (m == 0)
						{
							str_cell += "\n";
						}
					}
				}
			}
			return g;
		}

		#endregion 读码打码

		#region 半自动流程

		public void AutoRunPlc1()
		{
			while (GlobalVar.Instance.ThreadControl)
			{
				var result = h5u.ReadH5U(4232);
				if (result.Message != "11")
				{
					AddLog(1, "机器人不在自动运行中状态！");
					result = h5u.ReadH5U(4230);
					if (result.Message == "10")
					{
						result = h5u.WriteH5U(4230, "11");
						AddLog(1, "机器人警报");
					}
					Thread.Sleep(1000);
				}
				else if (GlobalVar.Instance.IsPause)
				{
					Thread.Sleep(1000);
					AddLog(0, "暂停中...");
				}
				else if (GlobalVar.Instance.isReadWarn)
				{
					AddLog(0, "读码超时报警");
					if (!GlobalVar.Instance.isOpneWarn)
					{
						//new Thread(() =>
						//{
						//    Invoke(new Action(OpenWarnForm));
						//}).Start();
					}
				}
				else if (GlobalVar.Instance.isPanRun)
				{
					Thread.Sleep(1000);
					AddLog(0, "搬运料盘等待...");
				}

				//else if (currplc_step1 == currplc_step2)
				//{
				//    AddLog(0, "位置相同等待...");
				//    Thread.Sleep(300);
				//}
				else
				{
					AddLog(0, "搬运1-进行到：" + GlobalVar.Instance.currplc_step1 + "步骤");
					switch (GlobalVar.Instance.currplc_step1)
					{
						case plcStep.请求取料:
							result = h5u.ReadH5U(4360);//NG料仓满料报警信号
							if (result.Message == "11")
							{
								AddLog(1, "机器人NG盘满报警!");
								break;
							}

							if ((GlobalVar.Instance.isFullNG && !GlobalVar.Instance.isReToNG))
							{
								AddLog(1, "请拿下NG盘!");
								return;
							}
							if ((!GlobalVar.Instance.isFullNG && GlobalVar.Instance.isReToNG))
							{
								AddLog(1, "请拿下NG盘!");
								return;
							}
							GlobalVar.Instance.isFullNG = false;
							GlobalVar.Instance.isReToNG = false;
							AddLog(0, "搬运1请求放料等待...");
							plc_fangliao(1, 4010);
							break;

						case plcStep.取料完成:
							GlobalVar.Instance.OrderData1 = new OrderData();
							GlobalVar.Instance.currplc_step1++;
							break;

						case plcStep.检测A:
							result = h5u.ReadH5U(4200);
							if (result.Message == "10")
							{
								GlobalVar.Instance.currplc_step1++;
								GlobalVar.Instance.currplc_step1++;
								break;
							}
							AddLog(0, "搬运1检测A面");
							//plc_jiance("A", 1, GlobalVar.Instance.currplc_step1, GlobalVar.Instance.currplc_step2, GlobalVar.Instance.OrderData1, 4020, GlobalVar.Instance.currplc_step1);
							break;

						case plcStep.检测B:
							result = h5u.ReadH5U(4202);
							if ((result.Message == "10") || GlobalVar.Instance.OrderData1.IsBaoFei)
							{
								GlobalVar.Instance.currplc_step1++;
								GlobalVar.Instance.currplc_step1++;
								break;
							}
							AddLog(0, "搬运1检测B面");
							//plc_jiance("B", 1, GlobalVar.Instance.currplc_step1, GlobalVar.Instance.currplc_step2, GlobalVar.Instance.OrderData1, 4022, GlobalVar.Instance.currplc_step1);
							break;

						case plcStep.进入打码A:
							result = h5u.ReadH5U(4204);
							if ((result.Message == "10") || GlobalVar.Instance.OrderData1.IsBaoFei)
							{
								GlobalVar.Instance.currplc_step1++;
								GlobalVar.Instance.currplc_step1++;
								break;
							}
							AddLog(0, "搬运1等待进入打码A面");
							plc_dama("A", 1, GlobalVar.Instance.OrderData1, GlobalVar.Instance.cellInfos_1, GlobalVar.Instance.comInfos_1, GlobalVar.Instance.homMat2D_dama_a1, GlobalVar.Instance.homMat2D_dama_b1, 4030);
							break;

						case plcStep.打码A完成:
							result = h5u.ReadH5U(4204);
							if ((result.Message == "10") || GlobalVar.Instance.OrderData1.IsBaoFei)
							{
								GlobalVar.Instance.currplc_step1++;
								break;
							}
							result = h5u.WriteH5U(4034, "11");//打码A面完成给信号
							if (result.IsSuccess)
							{
								GlobalVar.Instance.currplc_step1++;
								AddLog(0, "搬运1-A面打码完成!");
							}
							break;

						case plcStep.进入打码B:
							result = h5u.ReadH5U(4206);
							if ((result.Message == "10") || GlobalVar.Instance.OrderData1.IsBaoFei)
							{
								GlobalVar.Instance.currplc_step1++;
								GlobalVar.Instance.currplc_step1++;
								break;
							}
							AddLog(0, "搬运1等待进入打码B面");
							plc_dama("B", 1, GlobalVar.Instance.OrderData1, GlobalVar.Instance.cellInfos_1, GlobalVar.Instance.comInfos_1, GlobalVar.Instance.homMat2D_dama_a1, GlobalVar.Instance.homMat2D_dama_b1, 4032);
							break;

						case plcStep.打码B完成:
							if (GlobalVar.Instance.OrderData1.IsBaoFei)
							{
								GlobalVar.Instance.currplc_step1++;
								break;
							}
							//doMapping(GlobalVar.Instance.cellInfos_1, GlobalVar.Instance.comInfos_1, GlobalVar.Instance.OrderData1, "1");
							result = h5u.ReadH5U(4206);
							if ((result.Message == "10") || GlobalVar.Instance.OrderData1.IsBaoFei)
							{
								GlobalVar.Instance.currplc_step1++;
								break;
							}
							//打码B面完成给信号
							result = h5u.WriteH5U(4036, "11");//打码B面完成给信号
							if (result.IsSuccess)
							{
								GlobalVar.Instance.currplc_step1++;
								AddLog(0, "搬运1-B面打码完成!");
							}
							break;

						case plcStep.读码A:
							result = h5u.ReadH5U(4208);
							if ((result.Message == "10") || GlobalVar.Instance.OrderData1.IsBaoFei)
							{
								GlobalVar.Instance.currplc_step1++;
								break;
							}
							AddLog(0, "搬运1-A面读码");
							plc_duma("A", 1, GlobalVar.Instance.OrderData1, 4040, 4044);
							break;

						case plcStep.读码B:
							result = h5u.ReadH5U(4210);
							if ((result.Message == "10") || GlobalVar.Instance.OrderData1.IsBaoFei)
							{
								GlobalVar.Instance.currplc_step1++;
								break;
							}
							AddLog(0, "搬运1-B面读码");
							plc_duma("B", 1, GlobalVar.Instance.OrderData1, 4042, 4046);
							break;

						case plcStep.下料:
							result = h5u.ReadH5U(4360);//NG料仓满料报警信号
							if (result.Message == "11")
							{
								AddLog(1, "机器人NG盘满报警!");
								break;
							}
							if ((GlobalVar.Instance.isFullNG && !GlobalVar.Instance.isReToNG))
							{
								AddLog(1, "请拿下NG盘!");
								return;
							}
							if ((!GlobalVar.Instance.isFullNG && GlobalVar.Instance.isReToNG))
							{
								AddLog(1, "请拿下NG盘!");
								return;
							}
							GlobalVar.Instance.isFullNG = false;
							GlobalVar.Instance.isReToNG = false;
							AddLog(0, "搬运1下料-下料...");
							plc_xialiao(1, GlobalVar.Instance.OrderData1, 4014, 13);
							break;

						case plcStep.下料完成:
							if (GlobalVar.Instance.OrderData1.IsBaoFei)
							{
								// MySqlHelper.Add_Product("", "0", "", "", "0");
							}
							else
							{
								// MySqlHelper.Add_Product(OrderData1.Code, "1", "", "0", OrderData1.BadMark.ToString());
							}
							AddLog(0, "搬运1下料完成");
							GlobalVar.Instance.currplc_step1 = plcStep.请求取料;
							break;

						default:
							break;
					}
				}
				Thread.Sleep(50);
			}
		}

		public void AutoRunPlc2()
		{
			while (GlobalVar.Instance.ThreadControl)
			{
				var result = h5u.ReadH5U(4232);
				if (result.Message != "11")
				{
					AddLog(1, "机器人不在自动运行中状态！");
					result = h5u.ReadH5U(4230);
					if (result.Message == "10")
					{
						result = h5u.WriteH5U(4230, "11");
						AddLog(1, "机器人警报");
					}
					Thread.Sleep(1000);
				}
				else if (GlobalVar.Instance.IsPause)
				{
					Thread.Sleep(1000);
					AddLog(0, "暂停中...");
				}
				else if (GlobalVar.Instance.isPanRun)
				{
					Thread.Sleep(1000);
					AddLog(0, "搬运料盘等待...");
				}
				//else if (currplc_step1 == currplc_step2)
				//{
				//    AddLog(0, "位置相同等待...");
				//    Thread.Sleep(300);
				//}
				else
				{
					AddLog(0, "搬运2-进行到：" + GlobalVar.Instance.currplc_step2 + "步骤");
					switch (GlobalVar.Instance.currplc_step2)
					{
						case plcStep.请求取料:
							result = h5u.ReadH5U(4360);//NG料仓满料报警信号
							if (result.Message == "11")
							{
								AddLog(1, "机器人NG盘满报警!");
								break;
							}

							if ((GlobalVar.Instance.isFullNG && !GlobalVar.Instance.isReToNG))
							{
								AddLog(1, "请拿下NG盘!");
								return;
							}
							if ((!GlobalVar.Instance.isFullNG && GlobalVar.Instance.isReToNG))
							{
								AddLog(1, "请拿下NG盘!");
								return;
							}
							GlobalVar.Instance.isFullNG = false;
							GlobalVar.Instance.isReToNG = false;
							AddLog(0, "搬运1请求放料等待...");
							plc_fangliao(2, 4050);
							break;

						case plcStep.取料完成:
							AddLog(0, "搬运2放料");
							GlobalVar.Instance.OrderData2 = new OrderData();
							GlobalVar.Instance.currplc_step2++;
							Thread.Sleep(100);
							break;

						case plcStep.检测A:
							result = h5u.ReadH5U(4200);
							if (result.Message == "10")
							{
								GlobalVar.Instance.currplc_step2++;
								GlobalVar.Instance.currplc_step2++;
								break;
							}
							AddLog(0, "搬运2检测A面");
							//plc_jiance("A", 2, GlobalVar.Instance.currplc_step2, GlobalVar.Instance.currplc_step2, GlobalVar.Instance.OrderData2, 4060, GlobalVar.Instance.currplc_step2);
							break;

						case plcStep.检测B:
							result = h5u.ReadH5U(4202);
							if ((result.Message == "10") || GlobalVar.Instance.OrderData2.IsBaoFei)
							{
								GlobalVar.Instance.currplc_step2++;
								GlobalVar.Instance.currplc_step2++;
								break;
							}
							AddLog(0, "搬运2检测B面");
							//plc_jiance("B", 2, GlobalVar.Instance.currplc_step2, GlobalVar.Instance.currplc_step2, GlobalVar.Instance.OrderData2, 4062, GlobalVar.Instance.currplc_step2);

							break;

						case plcStep.进入打码A:
							result = h5u.ReadH5U(4204);
							if ((result.Message == "10") || GlobalVar.Instance.OrderData2.IsBaoFei)
							{
								GlobalVar.Instance.currplc_step2++;
								GlobalVar.Instance.currplc_step2++;
								break;
							}
							AddLog(0, "搬运2-A面等待打码");
							plc_dama("A", 2, GlobalVar.Instance.OrderData2, GlobalVar.Instance.cellInfos_2, GlobalVar.Instance.comInfos_2, GlobalVar.Instance.homMat2D_dama_a2, GlobalVar.Instance.homMat2D_dama_b2, 4070);
							break;

						case plcStep.打码A完成:
							result = h5u.ReadH5U(4204);
							if ((result.Message == "10") || GlobalVar.Instance.OrderData2.IsBaoFei)
							{
								GlobalVar.Instance.currplc_step2++;
								break;
							}
							//打码A面完成给信号
							result = h5u.WriteH5U(4074, "11");//打码A面完成给信号
							if (result.IsSuccess)
							{
								GlobalVar.Instance.currplc_step2++;
								AddLog(0, "搬运2-A面打码完成!");
							}
							break;

						case plcStep.进入打码B:
							result = h5u.ReadH5U(4206);
							if ((result.Message == "10") || GlobalVar.Instance.OrderData2.IsBaoFei)
							{
								GlobalVar.Instance.currplc_step2++;
								GlobalVar.Instance.currplc_step2++;
								break;
							}
							AddLog(0, "搬运2等待进入打码B面");
							plc_dama("B", 2, GlobalVar.Instance.OrderData2, GlobalVar.Instance.cellInfos_2, GlobalVar.Instance.comInfos_2, GlobalVar.Instance.homMat2D_dama_a2, GlobalVar.Instance.homMat2D_dama_b2, 4072);
							break;

						case plcStep.打码B完成:
							if (GlobalVar.Instance.OrderData2.IsBaoFei)
							{
								GlobalVar.Instance.currplc_step2++;
								break;
							}
							//doMapping(GlobalVar.Instance.cellInfos_2, GlobalVar.Instance.comInfos_2, GlobalVar.Instance.OrderData2, "2");
							result = h5u.ReadH5U(4206);
							if ((result.Message == "10") || GlobalVar.Instance.OrderData2.IsBaoFei)
							{
								GlobalVar.Instance.currplc_step2++;
								break;
							}
							//打码B面完成给信号
							result = h5u.WriteH5U(4076, "11");//打码B面完成给信号
							if (result.IsSuccess)
							{
								GlobalVar.Instance.currplc_step2++;
								AddLog(0, "搬运2-B面打码完成!");
							}
							break;

						case plcStep.读码A:
							result = h5u.ReadH5U(4208);
							if ((result.Message == "10") || GlobalVar.Instance.OrderData2.IsBaoFei)
							{
								GlobalVar.Instance.currplc_step2++;
								break;
							}
							AddLog(0, "搬运2扫码A面");
							plc_duma("A", 2, GlobalVar.Instance.OrderData2, 4080, 4084);
							break;

						case plcStep.读码B:
							result = h5u.ReadH5U(4210);
							if ((result.Message == "10") || GlobalVar.Instance.OrderData2.IsBaoFei)
							{
								GlobalVar.Instance.currplc_step2++;
								break;
							}
							AddLog(0, "搬运2扫码B面");
							plc_duma("B", 2, GlobalVar.Instance.OrderData2, 4082, 4086);
							break;

						case plcStep.下料:
							result = h5u.ReadH5U(4360);//NG料仓满料报警信号
							if (result.Message == "11")
							{
								AddLog(1, "机器人NG盘满报警!");
								break;
							}
							if ((GlobalVar.Instance.isFullNG && !GlobalVar.Instance.isReToNG))
							{
								AddLog(1, "请拿下NG盘!");
								return;
							}
							if ((!GlobalVar.Instance.isFullNG && GlobalVar.Instance.isReToNG))
							{
								AddLog(1, "请拿下NG盘!");
								return;
							}
							GlobalVar.Instance.isFullNG = false;
							GlobalVar.Instance.isReToNG = false;
							AddLog(0, "搬运2下料-下料...");
							plc_xialiao(2, GlobalVar.Instance.OrderData2, 4054, 14);
							break;

						case plcStep.下料完成:
							AddLog(0, "搬运2下料完成");
							if (GlobalVar.Instance.OrderData2.IsBaoFei)
							{
								// MySqlHelper.Add_Product("", "0", "", "", "0");
							}
							else
							{
								//  MySqlHelper.Add_Product(OrderData2.Code, "1", "", "0", OrderData2.BadMark.ToString());
							}
							GlobalVar.Instance.currplc_step2 = plcStep.请求取料;
							break;

						case plcStep.流程完成:
							AddLog(0, "搬运2-流程完成");

							break;

						default:
							break;
					}
				}
				Thread.Sleep(50);
			}
		}

		#endregion 半自动流程

		//---- 连接 打码机
		public void PrintConnect()
		{
			if (TcpRecive.Print.isConnect)
			{
				return;
			}
			TcpRecive.Print.serverIp = "127.0.0.1";
			TcpRecive.Print.port = 8080;
			TcpRecive.Print.threadStart();
			if (TcpRecive.Print.isConnect)
			{
				AddLog(0, "打码机连接成功！！！");
			}
			else
			{
				AddLog(1, "打码机连接失败！！！");
			}
		}

		//--- 设置居中
		public void CenterControlInParent(Control control)
		{
			// 设置控件的 Anchor 属性为 None，以便在调整位置时不受其他属性的影响
			control.Anchor = AnchorStyles.None;
			int x = (control.Parent.Width - control.Width) / 2;
			int y = (control.Parent.Height - control.Height) / 2;
			Console.WriteLine($"窗口宽度：{control.Parent.Width} 高度{control.Parent.Height}，panel宽度：{control.Width} 高度：{control.Height},x:{x},y:{y}");
			control.Location = new Point(x, y);
			// 重新设置 Anchor 属性，以便在窗体大小更改时控件仍然保持在中心
			//control.Anchor = AnchorStyles.None | AnchorStyles.Top | AnchorStyles.Bottom | AnchorStyles.Left | AnchorStyles.Right;
		}

		//--- 耗时 运动
		public void DoTimeZero()
		{
			//demoTCP.endTime = DateTime.Now;
			//TimeSpan elapsed = demoTCP.endTime - demoTCP.startTime;
			//AddLog(0, "时间: " + elapsed.TotalSeconds + " 秒,完成：" + demoTCP.total);
			//MessageBox.Show("时间: " + elapsed.TotalSeconds + " 秒,完成：" + demoTCP.total);
		}

		//获取用户列表
		public List<SysAdmins> GetAdminList()
		{
			List<SysAdmins> AdminList = new List<SysAdmins>();
			try
			{
				string Sql = "SELECT * FROM SysAdmins";
				DataTable dataTable = MySqlHelper.GetDataTable(MySqlHelper.Conn, CommandType.Text, Sql);
				//dgv_User.DataSource = dataTable;

				//dataTable.Columns["LoginName"].ColumnName = "用户名";
				//dataTable.Columns["LoginPwd"].ColumnName = "密码";
				//dataTable.Columns["DamaCtrl"].ColumnName = "打码控制";
				//dataTable.Columns["DumaCtrl"].ColumnName = "读码控制";
				//dataTable.Columns["SysSet"].ColumnName = "设置控制";
				//dataTable.Columns["SysLog"].ColumnName = "日志控制";
				//dataTable.Columns["Report"].ColumnName = "报表控制";
				//dataTable.Columns["Check"].ColumnName = "检测控制";
				//dataTable.Columns["UserManage"].ColumnName = "用户管理控制";
				//dataTable.Columns["BiaoCtrl"].ColumnName = "标定控制";
				//dataTable.Columns["PeiCtrl"].ColumnName = "配方控制";
				//dataTable.Columns["Status"].ColumnName = "用户状态";

				if (dataTable.Rows.Count > 0)
				{
					foreach (DataRow row in dataTable.Rows)
					{
						AdminList.Add(new SysAdmins()
						{
							LoginName = row["LoginName"].ToString(),
							Pwd = row["LoginPwd"].ToString(),
							LoginPwd = Register.Decrypt(row["LoginPwd"].ToString()),
							DamaCtrl = row["DamaCtrl"].ToString() == "1",
							DumaCtrl = row["DumaCtrl"].ToString() == "1",
							SysSet = row["SysSet"].ToString() == "1",
							SysLog = row["SysLog"].ToString() == "1",
							Report = row["Report"].ToString() == "1",
							Check = row["Check_"].ToString() == "1",
							UserManage = row["UserManage"].ToString() == "1",
							BiaoCtrl = row["BiaoCtrl"].ToString() == "1",
							PeiCtrl = row["PeiCtrl"].ToString() == "1",
							Status = row["Status_"].ToString() == "0",
							diy = row["diy"].ToString() == "1",
						});
					}
				}

				return AdminList;
			}
			catch (Exception ex)
			{
				Console.WriteLine("查询表失败:" + ex.ToString());
				//MessageBox.Show("查询表失败！");
				return AdminList;
			}
		}
	}
}